﻿using System;
using System.Web;

/// <summary>
///ChenxinModule 的摘要说明
///add by kimi 2010-3-2
///
/// </summary>
public class ChenxinModule : IHttpModule
{
    public ChenxinModule()
    {
        //
        //TODO: 在此处添加构造函数逻辑
        //
    }

    #region IHttpModule 成员

    public void Init(HttpApplication application)
    {
        application.AcquireRequestState += (new EventHandler(this.Application_AcquireRequestState));
        application.Error += new EventHandler(application_Error);
    }
    /// <summary>
    /// 判断是否为调试模式
    /// </summary>
    /// <returns></returns>
    bool isDebug()
    {
        try
        {
            object obj = System.Web.Configuration.WebConfigurationManager.GetSection("system.web/compilation");
            System.Web.Configuration.CompilationSection cs = obj as System.Web.Configuration.CompilationSection;
            return cs.Debug;
        }
        catch
        {
            return true;
        }
    }

    void application_Error(object sender, EventArgs e)
    {
        if (isDebug() == true)
        {
            return;
        }

        //非调试环境下纪录错误日志
        Exception ex = HttpContext.Current.Server.GetLastError().GetBaseException();
        try
        {
            string url = System.Web.HttpContext.Current.Request.Path.ToLower();
            string queryString = System.Web.HttpContext.Current.Request.QueryString.ToString();

            if (url.Contains("errorpage.aspx"))
            {
                return;
            }

            Chenxin.Lib.Passport.BLL.Cache_UserInfo user = null;
            Guid userId = Guid.Empty;
            if (!string.IsNullOrEmpty(HttpContext.Current.Request.Cookies["requestkey"].Value))
            {
                string strRequestKey = HttpContext.Current.Request.Cookies["requestkey"].Value;
                Chenxin.Lib.Cache.CacheService cs  = new Chenxin.Lib.Cache.CacheService( Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                string strCachedKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_REQUEST, strRequestKey);

                userId = (cs.GetGuid(strCachedKey) == null) ? Guid.Empty: (Guid)cs.GetGuid(strCachedKey);
            }
            
            try
            {
                user = new Chenxin.Lib.Passport.BLL.Cache_UserInfo(userId);
                user = user.GetCurrentUserInfo();
            }
            catch
            {

            }

            Chenxin.Lib.Passport.Entity.System_TraceInfo traceItem = new Chenxin.Lib.Passport.Entity.System_TraceInfo();

            traceItem.OprUserId = (user == null) ? Guid.Empty : user.UserId;
            traceItem.OprUserName = (user == null) ? "未登录" : user.UserName;
            traceItem.URL = url;
            traceItem.QueryString = queryString;
            traceItem.IPAddr = HttpContext.Current.Request.UserHostAddress;

            traceItem.Title = ex.Message;
            traceItem.Memo = ex.StackTrace;
            traceItem.Addtime = DateTime.Now;
            traceItem.RecordId = Guid.NewGuid();


            HttpContext.Current.Server.ClearError();
            Chenxin.Lib.Passport.DAL.System_TraceInfo.Add(traceItem);
        }
        catch
        { }

        System.Web.HttpContext.Current.Response.Redirect("~/ErrorPage.aspx?msg=" + ex.Message);

    }

    private void Application_AcquireRequestState(Object source, EventArgs e)
    {
        //if (isDebug()) { return; }

        HttpApplication Application = (HttpApplication)source;
        HttpResponse Response = Application.Context.Response;
        bool isAuth = false;
        string url = Application.Context.Request.Path.ToLower();
        string queryString = Application.Context.Request.QueryString.ToString();
        string strRequestKey = "";
        string userId = "";
        
        //过滤非aspx页面,解决VS2005调试环境下,ISAPI绑定其他资源文件问题
        if (!url.Contains(".aspx") && !url.Contains(".ashx"))// 
        {
            return;
        }

        if (queryString.Contains("op=fileupload") && !String.IsNullOrEmpty(Application.Context.Request.Params["folder"]))
        {
            string strCookies = Application.Context.Request.Params["folder"].ToString();
            string cookiename = "requestkey=";
            int cookiestartindex = strCookies.IndexOf(cookiename);
            string cookie = strCookies.Substring(cookiestartindex + cookiename.Length, 32);
            HttpContext.Current.Request.Cookies.Remove("requestkey");
            HttpCookie ckRequestKey = new HttpCookie("requestkey", cookie);
            HttpContext.Current.Request.Cookies.Add(ckRequestKey);
        }
        bool hasCookies = false;
        if ((HttpContext.Current.Request.Cookies["requestkey"] != null))
        {
            hasCookies = true;
            strRequestKey = HttpContext.Current.Request.Cookies["requestkey"].Value;
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
            string strCachedKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_REQUEST, strRequestKey);

            userId = cs.GetString(strCachedKey);
            if (cs.Hit)
            {
                isAuth = true;

                //cs.Delete(strCachedKey);

                cs.Set(strCachedKey, userId, DateTime.Now.AddMinutes(60));
            }
        }

        //-------------------------------------------------------------

        if (isAuth && !url.Contains("loginex.aspx") && !url.Contains("errorpage.aspx") && !url.Contains("exceltransfer.aspx"))
        {
            /* 记录操作日志 */
            Chenxin.Lib.Passport.BLL.Cache_UserInfo user = new Chenxin.Lib.Passport.BLL.Cache_UserInfo(new Guid(userId));
            user = user.GetCurrentUserInfo();
            /*
            Chenxin.Lib.Passport.Entity.System_TraceInfo logitem = new Chenxin.Lib.Passport.Entity.System_TraceInfo();
            logitem.OprUserId = user.UserId;
            logitem.URL = url;
            logitem.IPAddr = HttpContext.Current.Request.UserHostAddress;
            logitem.Memo = String.Empty;
            logitem.OprUserName = user.UserName;
            logitem.QueryString = queryString;
            logitem.Title = String.Empty;
            logitem.RecordId = Guid.NewGuid();
            logitem.Addtime = DateTime.Now;
            Chenxin.Lib.Passport.DAL.System_TraceInfo.Add(logitem);
            */
            if (!url.Contains("ajaxpro") && !url.Contains(".axd") && !url.Contains("ashx"))
            {
                //权限判断
                int idxSlash = url.LastIndexOf("/");
                string strUrl = url.Substring(idxSlash + 1);
                if (!user.ContainsPermit(strUrl))
                {
                    Application.Context.Response.Redirect("/errorpage.aspx?msg=没有此页面的访问权限", true);
                }
            }
        }

        if (isAuth || url.Contains("ajaxpro") || url.Contains(".axd") || url.Contains("loginex.aspx") || url.Contains("loginhandler.ashx") || url.Contains("personalinitpwd.aspx") || url.Contains("personalinitpwd.ashx") || url.Contains("abc.aspx") || url.Contains("exceltransfer.aspx"))
        {
            return;
        }
        else
        {
            if (!isAuth && url.Contains(".ashx"))
            {
                Application.Context.Response.Write(string.Format("{{success:'-1',msg:'{0}',data:''}}", "用户登录已过期，请重新登录cookie" + hasCookies.ToString()));
                Application.Context.Response.End();
                return;
            }
            else
            {
                //hejifeng add 2010-04-27
                string toUrl = System.Web.HttpUtility.UrlEncode(Application.Context.Request.Url.PathAndQuery);
                Application.Context.Response.Redirect("~/loginex.aspx?tourl=" + toUrl);
            }
            //Application.Context.Response.Write("<script>window.top.location.href='/loginex.aspx';</script>");
        }
    }

    public void Dispose()
    {
    }

    #endregion
}
